import 'package:flutter_novel/config/response_model.dart';
import 'package:flutter_novel/detail/bloc/home_detail_event.dart';
import 'package:flutter_novel/detail/bloc/home_detail_state.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_novel/detail/data/model/cartoon_recommend_entity.dart';
import 'package:flutter_novel/detail/data/model/cartoon_series_entity.dart';
import 'package:flutter_novel/detail/data/model/detail_model_entity.dart';
import 'package:flutter_novel/detail/data/repository/home_repository.dart';
import 'package:flutter_novel/widget/loading_util.dart';

class HomeDetailBloc extends Bloc<HomeDetailEvent, HomeDetailState> {
  HomeDetailBloc() : super(HomeDetailState()) {
    on<GetDetailDataEvent>(_onGetDetailData);
    on<UpdateOffsetEvent>(_updateOffset);
  }

  void _onGetDetailData(GetDetailDataEvent event, Emitter<HomeDetailState> emit) async {
    LoadingUtil.show();
    DetailModelData? detailModelData = await _getMainData();
    List<CartoonSeriesDataSeriesComics>? seriesList = await _getSeriesData();
    List<CartoonRecommendDataInfos>? recommendList = await _getRecommendData();
    LoadingUtil.dismiss();
    if (detailModelData != null && seriesList != null && recommendList != null) {
      emit(
        state.clone()
          ..detailModelData = detailModelData
          ..seriesList = seriesList
          ..recommendList = recommendList
          ..loadFinish = true,
      );
    } else {
      emit(state.clone()..loadFinish = true);
    }
  }

  void _updateOffset(UpdateOffsetEvent event, Emitter<HomeDetailState> emit) {
    double alpha = event.newOffset / 100;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    emit(
      state.clone()
        ..scrollOffset = event.newOffset
        ..alpha = alpha,
    );
  }

  /// 请求主数据
  Future<DetailModelData?> _getMainData() async {
    ResponseModel responseModel = await HomeRepository.getMainData<DetailModelData>();
    return responseModel.data;
  }

  /// 请求系列数据
  Future<List<CartoonSeriesDataSeriesComics>?> _getSeriesData() async {
    ResponseModel responseModel = await HomeRepository.getSeriesData<CartoonSeriesData>();
    CartoonSeriesData? cartoonSeriesData = responseModel.data;
    return cartoonSeriesData?.seriesComics;
  }

  /// 请求推荐数据
  Future<List<CartoonRecommendDataInfos>?> _getRecommendData() async {
    ResponseModel responseModel = await HomeRepository.getRecommendData<CartoonRecommendData>();
    CartoonRecommendData? cartoonRecommendData = responseModel.data;
    return cartoonRecommendData?.infos;
  }
}
